﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.IO;
using Windows.Storage.Pickers;
using Windows.Storage;
using MyVideoManager.DataModel;
using Windows.Storage.Streams;
//using System.Management;
using Windows.System.Profile;

namespace MyVideoManager.Common
{

    //TODO: a completer
    enum extansionFichier
    {
        AVI,
        MP4,
        WMA,
        MKV,
        MPEG, //Ajouté le 03/12/2012 Amor
        FLV   //Pareil
    }

    class AnalyseFichier
    {
        private String cheminFichier;
        private List<String>lstTitre;
        private String lettre;
        private String idPeriph;
        private List<Peripherique>lstPeripherique; // permet de stocké la liste des USB deja analysé   

        public AnalyseFichier()
        {
            this.lstTitre = new List<string>();
            this.lstPeripherique = new List<Peripherique>();
        }

        public Dossier getDossier()
        {
            Dossier monDossier = new Dossier();

            return monDossier;
        }

        public async void afficherFolderPicker()
        {

            FolderPicker folderPicker = new FolderPicker();
            folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;


            folderPicker.FileTypeFilter.Add(".docx");
            folderPicker.FileTypeFilter.Add(".xlsx");
            folderPicker.FileTypeFilter.Add(".pptx");

            StorageFolder folder = await folderPicker.PickSingleFolderAsync();



            if ( folder != null)
            {
                IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();
                
                // on recupere le nom du lecteur
                this.lettre = getLettreCheminDossier(folder.Path);

                // on recupere l'id du periph qui est branché sur le lecteur
                getIdHardware();


                //TODO: enregistré le numero du perif dans la liste des peripherique deja analysé.

               // Dossier monDossier = new Dossier(folder.Name); //Permet de tout recuperer dans une classe dossier
                //Mediatheque maMediatheque = new Mediatheque();

                foreach (StorageFile file in files)
                {
                    addTitre(file.Name);
                    //monDossier.addFilm(file.Name);
                }

                //maMediatheque.addDossier(monDossier);
            }
           

        }

        private String getLettreCheminDossier(String path)
        {
            return path.Substring(0, 1); // on prend la 1er lettre.
        }


        private async void getIdHardware()
        {
            var selector = Windows.Devices.Portable.StorageDevice.GetDeviceSelector();
            var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(selector);

            foreach (Windows.Devices.Enumeration.DeviceInformation device in devices)
            {
                // Get device root folder
                StorageFolder rootFolder = Windows.Devices.Portable.StorageDevice.FromId(device.Id);
                if (this.lettre.Equals((rootFolder.Path).Substring(0, 1)))
                {

                    this.idPeriph = device.Id;
                }
                
            }
        }

        private string GetHardwareId()
        {
            var token = HardwareIdentification.GetPackageSpecificToken(null);
            var hardwareId = token.Id;
            var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);

            byte[] bytes = new byte[hardwareId.Length];
            dataReader.ReadBytes(bytes);

            return BitConverter.ToString(bytes);
        }
        /*
        private void getIdUSb()
        {
            foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType='USB'").Get())
            {
                // associate physical disks with partitions

                foreach (ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
                {
                   // Console.WriteLine("Partition=" + partition["Name"]);

                    // associate partitions with logical disks (drive letter volumes)

                    foreach (ManagementObject disk in new ManagementObjectSearcher(
                        "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass =Win32_LogicalDiskToPartition").Get())
                    {
                        if (disk["Name"].Equals(this.lettre))
                        {
                          ManagementObject usb=  new ManagementObject("Win32_PhysicalMedia.Tag='"+ drive["DeviceID"] + "'");
                            String id=usb["SerialNumber"].ToString();
                          this.lstPeripherique.Add(new Peripherique(id));
                        }
                       // Console.WriteLine("Disk=" + disk["Name"]);
                    }
                }

                // this may display nothing if the physical disk

                // does not have a hardware serial number

               /* Console.WriteLine("Serial="
                 + new ManagementObject("Win32_PhysicalMedia.Tag='"
                 + drive["DeviceID"] + "'")["SerialNumber"]);
                
            }
        }
         * */
        public void filtrageDossier(string chemin)
        {
            /*
            String[] files = Directory.GetFiles("c:\\test");

            for (int i = 0; i < files.Length; i++)
            {
                FileInfo F = new FileInfo(files[i]);
                Console.Out.WriteLine(F.Name);
            } 
             * */
        }

        public void addTitre(String monTitre)
        {
            this.lstTitre.Add(monTitre);
        }
        
        /// <summary>
        /// 
        /// Analyse l'extantion
        /// </summary>
        /// <param name="nomFichier"></param>
        /// <returns>True si le fichier est un film.</returns>
        private bool estLisible(string nomFichier)
        {
            int positionPoint = nomFichier.LastIndexOf('.');
            string extansion = nomFichier.Substring(positionPoint, nomFichier.Length);


            if (extansion.Equals("avi"))
            {
                return true;
            }
            else if (extansion.Equals("mp4"))
            {

            }
            return true;


        }



    }
}
